package com.alex.utils.wordpress;

import java.io.File;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;

public class RemoveLinksFromThemes {

	private static Pattern pattern = Pattern.compile("https?://[^'\"\\s\\\\]+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			System.out.println("Specify directory");
			return;
		}
		
		System.out.println("Removing links from " + args[0]);
		
		Iterator<File> it = FileUtils.iterateFiles(new File(args[0]), new String[] { "php" }, true);
		while (it.hasNext()) {
			File file = it.next();
			processFile(file);
		}
		
		System.out.println("Done");
	}

	private static void processFile(File file) {
		try {
			String str = FileUtils.readFileToString(file);
			Matcher matcher = pattern.matcher(str);
			StringBuffer sb = new StringBuffer(str.length());
			
			while (matcher.find()) {
				String link = matcher.group();
				if (!link.endsWith(".dtd")) {
					matcher.appendReplacement(sb, "/");
				}
			}
			matcher.appendTail(sb);
			
			FileUtils.writeStringToFile(file, sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
